import { replaceProfile } from "@/api/modules/model/profile";
import { replaceSchema } from "@/api/modules/model/schema";
import JsonSchemaEditor from "@/components/JsonSchemaForm/JsonSchemaForm.vue";
import { AuthBtns, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { showTips } from "@/utils/util";
import { defineComponent } from "vue";
import { useRoute } from "vue-router";
// import DialogBox from "@/components/DialogBox";
// import JsonView from "../components/PreviewProfile";
import { parseProfileFormGateway, parseSchemaConfig, parseSchemaFromGateway } from "./../../../../utils/schema";
import jsonpath from "jsonpath";

/**
 * 设备参数信息,scheme中的config下面子设备参数信息（排除subdevice节点）
 * 相关参数：设备接入端口、地址、采集周期、上报周期
 */
export default defineComponent({
	emits: [],
	setup() {
		const route = useRoute();

		//设备参数配置模型
		const schema = ref<any>(inject(SchemaNodeKey.gatewaySchema));
		const profile = ref<any>(inject(SchemaNodeKey.gatewayProfile));
		const disabledMod = inject<any>(AuthBtns.disabledMod);
		const refreshGatewayDetail = () => {
			mittBus.emit("refreshGatewayDetail");
		};
		const saveProfile = () => {
			//插入subdevice数据
			let oldProfile = parseProfileFormGateway(profile.value);
			let submitData = JSON.parse(JSON.stringify(gatewayProfile.value));
			submitData.subdevice = oldProfile.subdevice;
			replaceProfile({ idSn: route.query.sn || route.query.id, data: submitData }).then(res => {
				let ok = showTips(res.code, "参数配置");
				if (ok) {
					refreshGatewayDetail();
				}
			});
		};
		const saveSchema = () => {
			if (disabledMod.value) return;
			//追加原始设备配置
			let oldSchema = parseSchemaFromGateway(schema.value);
			let submitData = JSON.parse(JSON.stringify(jsonRoot.root));
			submitData.properties.subdevice = oldSchema.subdevice || {};
			replaceSchema({ idSn: route.query.sn || route.query.id, data: submitData }).then(res => {
				let ok = showTips(res.code, "设备配置");
				if (ok) {
					saveProfile();
					// refreshGatewayDetail();
				}
			});
		};

		let gatewaySchema = ref<any>({});
		let gatewayProfile = ref<any>({});
		//缓存subdevice数据
		const jsonRoot = reactive({
			root: {}
		});
		onBeforeMount(() => {
			initSchema();
		});
		watch(
			() => schema.value,
			() => {
				initSchema();
			}
		);
		//初始化上报数据，没有模型就自动增加
		const initSchema = () => {
			gatewaySchema.value = parseSchemaConfig(schema.value);
			gatewayProfile.value = parseProfileFormGateway(profile.value);
			jsonRoot.root = gatewaySchema.value;
			const applySchema = (value: any, path: string) => {
				//当前有相同Schema的key不执行
				if (!jsonpath.query(gatewaySchema.value.properties, `$.${path}`).length) {
					if (typeof value == "object") {
						jsonpath.value(gatewaySchema.value.properties, `$.${path}`, { type: "object" });
						for (let ck in value) {
							let cPath = path ? path + ".properties." + ck + "" : ck;
							jsonpath.value(gatewaySchema.value.properties, `$.${cPath}`);
							applySchema(value[ck], cPath);
						}
					} else {
						jsonpath.value(gatewaySchema.value.properties, `$.${path}`, { type: typeof value });
					}
				}
			};
			for (let key in gatewayProfile.value) {
				applySchema(gatewayProfile.value[key], key);
			}
			if (gatewaySchema.value.properties) {
				delete gatewaySchema.value.properties[SchemaNodeKey.subdevice];
				delete gatewaySchema.value.properties[SchemaNodeKey.sensor];
				delete gatewayProfile.value[SchemaNodeKey.subdevice];
			}
		};

		// const dialogVisible = ref<boolean>(false);
		return () => {
			return (
				<div class="block-basic p-8">
					{/* <DialogBox
						title="查看JSON"
						class="dialog-dense"
						v-model:visible={dialogVisible.value}
						footerLabel={["关闭"]}
						width="550px"
					>
						<JsonView profile={gatewayProfile.value} schema={jsonRoot.root} />
					</DialogBox> */}
					<div class="flex mb-4 justify-between">
						<div class="flex">
							<el-button type="primary" plain onClick={() => saveSchema()} disabled={disabledMod.value}>
								保存
							</el-button>
							{/* <el-button type="primary" plain onClick={() => saveProfile()}>
								保存profile
							</el-button> */}
						</div>
						{/* <el-button class="ml-auto" link type="primary" onClick={() => (dialogVisible.value = true)}>
							预览JSON
						</el-button> */}
					</div>
					<JsonSchemaEditor
						class="w-full"
						value={jsonRoot}
						lang="zh_CN"
						jsonValue={gatewayProfile.value}
						disabled={disabledMod.value}
					/>
				</div>
			);
		};
	}
});
